package com.maysham.tripod.config;

import com.maysham.tripod.config.auth.UserConfig;
import com.maysham.tripod.model.User;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;
import java.util.Optional;

public class CoderAuditorImpl implements AuditorAware<User> {
    @Resource
    private UserConfig userConfig;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    public Optional<User> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            User admin = new User();
            admin.setId("admin");
            admin.setUsername(userConfig.getName());
            admin.setPassword(passwordEncoder.encode(userConfig.getPwd()));
            return Optional.of(admin);
        }
        return Optional.of((User) authentication.getPrincipal());
    }
}
